package com.zhuoyian.zyalibrary.util;

import java.util.Locale;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.zhuoyian.zyalibrary.model.ARModel;
import com.zhuoyian.zyalibrary.model.Versions;
import com.zhuoyian.zyalibrary.service.VersionsService;
import com.zhuoyian.zyalibrary.util.DLUtil.DownLoadState;

/**
 * 更新辅助�?
 * 
 * @author Wiley
 */
@SuppressLint("HandlerLeak")
public class VersionUtil {
	private Context context;
	private Handler handler;
	private Versions ver;
	private String verstr;
	private String pbindKey;
	private String packId;
	private boolean isAuto;// 自动更新

	public void setAuto(boolean isAuto) {
		this.isAuto = isAuto;
	}

	/**
	 * 没有版本，常规更新下暂时不更新版本�?更新版本未完�?
	 */
	public static final int GETVERSION_FALSE = 184614;

	private int fileSize = 0, downLoadFileSize = 0;
	private String fileName;

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public VersionUtil(Context context, Handler handler, String pbindKey,
			String packId) {
		this.context = context;
		this.handler = handler;
		this.packId = packId;
		this.pbindKey = pbindKey;
	}

	/**
	 * 获取版本信息
	 */
	public void start() {
		if (goodNet()) {
			// �?��获取版本信息
			getVersion();
		} else {
			// 没有网络算作获取版本信息失败
			if (handler != null) {
				handler.sendEmptyMessage(GETVERSION_FALSE);
			}
		}
	}

	/**
	 * 获取当前应用的版本信�?
	 */
	public void getVersion() {
		VersionsService service = new VersionsService(context);
		service.GetNewVersions(hand, pbindKey, packId);
	}

	public Handler hand = new Handler() {

		@Override 
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case StaticSetting.RESULT_OK:
				Bundle bund = msg.getData();
				ARModel model = (ARModel) bund.getSerializable("result");
				if (model != null) {
					if (model.getResultCode().equals(ARModel.RESULT_OK)) {
						JSONObject obj;
						try {
							L.e(model.getReusltContent());
							obj = new JSONObject(model.getReusltContent());
							ver = JSONHelper.parseObject(obj, Versions.class);
							if (TextUtils.isEmpty(ver.getPath()))
								return;
							// 准备提示更新
							doNewVersionUpdate();
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
				break;
			case 333:
				pb.setMax(fileSize);
				buildNumPart();
				break;
			}
			super.handleMessage(msg);
		}

	};
	private boolean isupdate = false;

	/**
	 * 判断语言是否是中�?
	 * 
	 * @return
	 */
	private boolean isZh() {
		Locale locale = context.getResources().getConfiguration().locale;
		String language = locale.getLanguage();
		if (language.endsWith("zh"))
			return true;
		else
			return false;
	}

	Dialog dialog;

	private void doNewVersionUpdate() {
		if (isAuto) {
			// 如果�?��了自动更新则不需要再弹出提示直接进行下载更新
			Update();
			return;
		}
		L.e("start update new versions");
		TextView tv = new TextView(context);
		if (isZh() && ver.getMessageCN() != null
				&& !ver.getMessageCN().equals("")) {
			verstr = ver.getMessageCN();
		} else {
			verstr = ver.getMessageEN();
		}
		int px = Util.dip2px(context, 10);
		tv.setPadding(px, px * 2, px, px * 2);
		tv.setTextColor(Util.ConvertColorToInt("555555"));
		tv.setText(verstr.replace("\\n", "\n"));
		dialog = new Dialog(context);
		dialog.show(context.getString(Util.getStringId(context,
				"zya_version_dialog_title")), "", tv, context.getString(Util
				.getStringId(context, "zya_version_dialog_lbtn")),
				context.getString(Util.getStringId(context,
						"zya_version_dialog_rbtn")),
				new Dialog.OnClickListener() {

					@Override
					public void onClick(Dialog dialog, View view) {

					}
				}, new Dialog.OnClickListener() {

					@Override
					public void onClick(Dialog dialog, View view) {
						// 准备�?��更新
						isupdate = true;
						Update();
					}
				}, new Dialog.OnDismissListener() {

					@Override
					public void onDismiss() {
						if (isupdate == false) {
							if (handler != null)
								// 不更新版�?
								handler.sendEmptyMessage(GETVERSION_FALSE);
						}
					}
				}, true, false);

	}

	private ProgressBar pb;
	private TextView tvPart, tv_downtitle;

	@SuppressLint("NewApi")
	protected void Update() {
		// 如果�?��了自动更新则不需要绘制视�?
		if (!isAuto) {
			// 更新面板
			LinearLayout layout = new LinearLayout(context);
			layout.setPadding(dip2px(context, 15), dip2px(context, 15),
					dip2px(context, 15), dip2px(context, 15));
			layout.setOrientation(LinearLayout.VERTICAL);
			layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
					LayoutParams.WRAP_CONTENT));
			// 下载进度�?
			pb = new ProgressBar(context, null,
					android.R.attr.progressBarStyleHorizontal);

			pb.setProgressDrawable(context.getResources().getDrawable(
					Util.getDrawableId(context, "zya_version_progress_style")));

			// 下载进度文字提示
			LinearLayout layout1 = new LinearLayout(context);
			tvPart = new TextView(context);
			tvPart.setTextColor(Util.ConvertColorToInt("#555555"));
			tvPart.setText(Html
					.fromHtml("0KB/<font color=\"#fd7100\">...</font>"));
			tvPart.setLayoutParams(new LinearLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
			tv_downtitle = new TextView(context);
			tv_downtitle.setLayoutParams(new LinearLayout.LayoutParams(
					LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 1));
			tv_downtitle.setTextColor(Util.ConvertColorToInt("#555555"));
			tv_downtitle.setText(Html.fromHtml(context.getString(Util
					.getStringId(context, "zya_version_download_done"))
					+ "<font color=\"#fd7100\">0%</font>"));

			LayoutParams lpar = new LayoutParams(new LinearLayout.LayoutParams(
					LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
			lpar.setMargins(0, 0, 0, Util.dip2px(context, 5));
			layout1.setLayoutParams(lpar);
			layout1.addView(tv_downtitle);
			layout1.addView(tvPart);

			layout.addView(layout1);
			layout.addView(pb);

			dialog = new Dialog(context);
			dialog.show(context.getString(Util.getStringId(context,
					"zya_version_download_title")), "", layout, context
					.getString(Util.getStringId(context,
							"zya_version_download_lbtn")), "",
					new Dialog.OnClickListener() {

						@Override
						public void onClick(Dialog dialog, View view) {
							if (dlutil != null)
								dlutil.setStop(true);
						}
					}, null, null, true, false);
		}
		// �?��下载文件
		dlutil = new DLUtil(ver.getPath(), fileName);
		dlutil.setOnDownLoadListener(new DLUtil.OnDownLoadListener() {

			@Override
			public void onDone(DownLoadState dlstate, String filepath,
					String downloadid) {
				switch (dlstate) {
				case SUCCESS:
					// 执行安装，直接采用静默安�?
					ApkControll.install(filepath, 3, context);
					break;
				case FAIL:
					if (handler != null)
						handler.sendEmptyMessage(GETVERSION_FALSE);
					break;
				default:
					break;
				}
				// 关闭弹出�?
				if (dialog != null) {
					dialog.dismiss();
				}
			}

			@Override
			public void onChange(int filesize, int downfilesize) {
				// 自动下载的状态下不需要更新视�?
				if (!isAuto) {
					fileSize = filesize;
					downLoadFileSize = downfilesize;
					 L.e("fileSize:" + fileSize + "  downLoadFileSize:"
					 + downLoadFileSize);
					hand.sendEmptyMessage(333);
				}
			}
		});
		dlutil.start();
	}

	private DLUtil dlutil;

	/**
	 * 刷新更新进度
	 */
	protected void buildNumPart() {
		tvPart.setText(Html
				.fromHtml(downLoadFileSize / 1000
						+ "KB/<font color=\"#fd7100\">" + fileSize / 1000
						+ "KB</font>"));
		int p = (int) ((downLoadFileSize * 100) / fileSize);
		if (p > 100) {
			p = 100;
		}
		tv_downtitle.setText(Html.fromHtml(context.getString(Util.getStringId(
				context, "zya_version_download_done"))
				+ "<font color=\"#fd7100\">" + p + "%</font>"));
		pb.setProgress(downLoadFileSize);
	}

	public int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 获取当前的版本号
	 * 
	 * @return
	 */
	protected int getVerCode() {
		int verCode = -1;
		try {
			verCode = context.getPackageManager().getPackageInfo(
					context.getApplicationContext().getPackageName(), 0).versionCode;
		} catch (NameNotFoundException e) {
			// Log.e(TAG, e.getMessage());
		}
		return verCode;
	}

	/**
	 * 判断是否有网�?
	 * 
	 * @return
	 */
	@SuppressWarnings("static-access")
	public boolean goodNet() {
		try {
			ConnectivityManager manager = (ConnectivityManager) context
					.getSystemService(context.CONNECTIVITY_SERVICE);
			NetworkInfo networkinfo = manager.getActiveNetworkInfo();
			if (networkinfo == null || !networkinfo.isAvailable())
				return false;
			else
				return true;
		} catch (Exception ex) {
			return false;
		}
	}
}
